import { onBeforeMount, onBeforeUnmount, reactive } from "vue";
export const useTouchDir = (
  callback: (key: "ArrowUp" | "ArrowDown" | "ArrowLeft" | "ArrowRight") => void
) => {
  const startPoint = reactive({ clientX: 0, clientY: 0 });

  const onTouchStart = (e: TouchEvent) => {
    const touch = e.changedTouches[0];
    if (touch) {
      Object.assign(startPoint, {
        clientX: Math.trunc(touch.clientX),
        clientY: Math.trunc(touch.clientY),
      });
    }
  };

  const onTouchEnd = (e: TouchEvent) => {
    const touch = e.changedTouches[0];
    if (touch) {
      const moveX = Math.trunc(touch.clientX) - startPoint.clientX;
      const moveY = Math.trunc(touch.clientY) - startPoint.clientY;
      let key: "ArrowUp" | "ArrowDown" | "ArrowLeft" | "ArrowRight";
      if (Math.abs(moveX) > Math.abs(moveY)) {
        key = moveX > 0 ? "ArrowRight" : "ArrowLeft";
      } else {
        key = moveY > 0 ? "ArrowDown" : "ArrowUp";
      }
      return callback(key);
    }
  };

  onBeforeMount(() => {
    document.addEventListener("touchstart", onTouchStart);
    document.addEventListener("touchend", onTouchEnd);
  });

  onBeforeUnmount(() => {
    document.removeEventListener("touchstart", onTouchStart);
    document.removeEventListener("touchend", onTouchEnd);
  });
};
